package com.rw.coco.data.data.mapper;

import com.rw.coco.api.data.model.AccountModel;
import com.rw.coco.api.data.persistence.simple.SimpleAccountMapper;
import com.rw.coco.data.data.bean.FileAccountModel;
import com.rw.coco.data.data.util.BeanUtil;
import com.rw.tool.util.io.FileIOUtil;
import com.rw.tool.util.io.file.BeanFile;
import com.rw.tool.util.io.file.wrapper.FileQueryWrapper;
import com.rw.tool.util.json.JsonUtil;

import java.io.File;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class FileAccountMapper extends SimpleAccountMapper {
    private static final String ACCOUNT_DIR_PATH = "\\account\\";

    private final BeanFile<FileAccountModel> beanFile;

    public FileAccountMapper(String workPath) {
        File file = new File(workPath, ACCOUNT_DIR_PATH);
        FileIOUtil.mkDirs(file);
        this.beanFile = new BeanFile<>(file, FileAccountModel.class);
    }

    private FileAccountModel convert(AccountModel data) {
        return JsonUtil.convertObj(data, FileAccountModel.class);
    }

    private AccountModel reconvert(FileAccountModel data) {
        return JsonUtil.convertObj(data, AccountModel.class);
    }

    private FileAccountModel removeId(FileAccountModel data) {
        return BeanUtil.removeIdProp(data, FileAccountModel.class);
    }

    @Override
    public void insert(AccountModel data) {
        FileAccountModel accountModel = JsonUtil.convertObj(data, FileAccountModel.class);
        beanFile.insert(accountModel);
    }

    @Override
    public void insertAll(Collection<AccountModel> dataList) {
        List<FileAccountModel> modelList = dataList.stream()
                .map(data -> JsonUtil.convertObj(data, FileAccountModel.class))
                .collect(Collectors.toList());

        beanFile.insertAll(modelList);
    }

    @Override
    public void delete(Serializable id) {
        beanFile.deleteById(id);
    }

    @Override
    public void deleteAll(AccountModel data) {
        beanFile.delete(BeanUtil.getQueryWrapper(convert(data)));
    }

    @Override
    public void update(AccountModel data) {
        FileAccountModel accountModel = convert(data);
        beanFile.update(BeanUtil.getIdWrapper(accountModel), removeId(accountModel));
    }

    @Override
    public AccountModel selectOne(Serializable id) {
        return beanFile.selectById(id);
    }

    @Override
    public List<AccountModel> selectList(AccountModel data) {
        FileAccountModel model = convert(data);
        FileQueryWrapper queryWrapper = BeanUtil.getQueryWrapper(model);
        List<FileAccountModel> modelList = beanFile.selectList(queryWrapper);
        return modelList.stream().map(this::reconvert).collect(Collectors.toList());
    }

    @Override
    public List<AccountModel> selectList(Collection<? extends Serializable> id) {
        return beanFile.selectList(id).stream().map(this::reconvert).collect(Collectors.toList());
    }
}
